//
//  AudioObserver.m
//  Do Not Disturb
//
//  Created by Chris Karr on 8/30/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "AudioObserver.h"
#import "DNDDefines.h"

@implementation AudioObserver

- (NSString *) getName
{
	return @"Audio";
}

- (void) scan
{
	NSMutableDictionary * dict = [NSMutableDictionary dictionary];
	[dict setValue:[NSDate date] forKey:@"date"];
	[dict setValue:[NSString stringWithFormat:@"Audio: Current Volume - %0.3f", volume] forKey:@"name"];

	[[NSDistributedNotificationCenter defaultCenter] postNotificationName:DND_UPDATE object:@"AudioObserver" userInfo:dict];
}

- (AudioObserver *) init
{
	if (self = [super init])
	{
		volume = 0.0;
		
		input = [[MTCoreAudioDevice defaultInputDevice] retain];
		
		[input setDelegate:self];
		[input setIOTarget:self withSelector:@selector(ioForDevice:timeStamp:inputData:inputTime:outputData:outputTime:clientData:) 
		 	withClientData:nil];
		
		[input deviceStart];
	}
	
	return self;
}

- (void) audioDeviceStartDidFail:(MTCoreAudioDevice *) theDevice forReason:(OSStatus) theReason
{
	NSLog (@"error 0x%x", theReason);
}

- (OSStatus) ioForDevice:(MTCoreAudioDevice *) theDevice timeStamp:(const AudioTimeStamp *) inNow 
	inputData:(const AudioBufferList *) inInputData inputTime:(const AudioTimeStamp *) inInputTime outputData:(AudioBufferList *) 
	outOutputData outputTime:(const AudioTimeStamp *) inOutputTime clientData:(void *) inClientData
{
	unsigned count = inInputData->mBuffers[0].mDataByteSize;
	
	volume = 0.0;
	
	float * data = inInputData->mBuffers[0].mData;

	int i = 0;
	for (i = 0; i < count; i++)
	{
		if (data[i] > volume && data[i] <= 1.0)
			volume = data[i];
	}

	return noErr;
}

@end
